package io.renren.modules.app.controller;


import com.baomidou.mybatisplus.mapper.Condition;
import io.renren.common.annotation.WebApi;
import io.renren.common.response.BaseRequest;
import io.renren.common.response.Response;
import io.renren.common.utils.BarcodeUtil;
import io.renren.common.utils.Query;
import io.renren.common.utils.R;
import io.renren.modules.app.dto.ListOutOrderDTO;
import io.renren.modules.app.dto.OutOrderDTO;
import io.renren.modules.app.enums.OutOrderStatusEnum;
import io.renren.modules.app.reponse.OutOrderRes;
import io.renren.modules.app.request.intoorder.DetailInOrderReq;
import io.renren.modules.app.request.intoorder.ListInOrderReq;
import io.renren.modules.app.service.ApiService;
import io.renren.modules.generator.entity.OutOrderEntity;
import io.renren.modules.generator.entity.OutOrderItemEntity;
import io.renren.modules.generator.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * APP测试接口
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-03-23 15:47
 */
@RestController
@RequestMapping("/api")
@Api(
        "出库订单接口"
)
public class OtOrderController {


    @Autowired
    OutOrderService outOrderService;

    @Autowired
    OutOrderItemService outOrderItemService;

    @Value("${file.upload-folder}")
    private String upFile;

    @GetMapping("getBarcode")
    @ApiOperation("获取二维码")
    public R getBarcode(@RequestParam("orderNo") String orderNo) {
        File file = new File(upFile);
        if (!file.exists()) {
            file.mkdirs();
        }
        BarcodeUtil.generateFile(orderNo, upFile + orderNo + ".png");
        return R.ok().put("url", "/file/images/" + orderNo + ".png");
    }

    @GetMapping("getOorderNo")
    @ApiOperation("获取出库单订单号")
    public R getOorderNo() {
        StringBuffer prefix = new StringBuffer("O");
        LocalDateTime ldt = LocalDateTime.now();
        prefix.append(ldt.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")));
        return R.ok().put("data", prefix.toString());
    }

    @Autowired
    PositionService positionService;

    @Autowired
    StockService stockService;

    @Autowired
    ItemService itemService;

    @GetMapping("getOutOrder")
    @ApiOperation("出库单详情")
    public R getOutOrder(@RequestParam("id") String id) {
        OutOrderRes response = new OutOrderRes();
        if (StringUtils.isNotEmpty(id)) {
            OutOrderEntity order = outOrderService.selectById(id);
            if (order != null) {
                response.setCreateTime(order.getCreateTime());
                response.setCreateUser(order.getCreateUser());
                response.setOrderNo(order.getOrderNo());
                response.setStatus(order.getStatus());
                response.setStatusStr(OutOrderStatusEnum.getTextByValue(order.getStatus()));
                List<OutOrderItemEntity> items = outOrderItemService.selectList(Condition.create().eq("order_no", order.getOrderNo()));
                List<OutOrderRes.OutOrderItem> orderItems = new ArrayList<>();
                items.forEach(x -> {
                    OutOrderRes.OutOrderItem item = new OutOrderRes.OutOrderItem();
                    BeanUtils.copyProperties(x, item);
//                    item.setAreaCode(x.getAreaCode());
//                    item.setItemGuid(x.getItemGuid());
//                    item.setItemId(x.getItemId());
//                    item.setOrderNo(x.getOrderNo());
//                    item.setProportion(x.getProportion());
//                    item.setPsCode(x.getPsCode());
//                    item.setQuantity(x.getQuantity());
                    item.setName(itemService.selectById(x.getItemId()).getName());
//                    item.setTrueQuantity(x.getTrueQuantity());
                    orderItems.add(item);
                });
                response.setOrderItems(orderItems);
            }
        }
        return R.ok().put("data", response);
    }

    @WebApi
    @PostMapping("getoutofwarehousetotal")
    @ApiOperation("获取出库单的总数量")
    public Response getoutofwarehousetotal(@RequestBody BaseRequest request) {
        return Response.ok(outOrderService.selectCount(Condition.create().eq("status", OutOrderStatusEnum.初始化.getValue())));
    }

    @Autowired
    ApiService apiService;

    @WebApi
    @PostMapping("getoutofwarehouselist")
    @ApiOperation("获取出库单列表")
    public Response getoutofwarehouselist(@RequestBody ListInOrderReq request) {
        List<ListOutOrderDTO> response = new ArrayList<>();
        Condition condition = Condition.create();
        condition.eq(StringUtils.isNotBlank(request.getCode()), "order_no", request.getCode());
        if (request.getStatus() > 0) {
            condition.eq("status", request.getStatus());
        } else {
            condition.eq("status", OutOrderStatusEnum.初始化.getValue());
        }
        condition.ge(!Objects.isNull(request.getStartdate()), "create_time", request.getStartdate());
        condition.ge(!Objects.isNull(request.getEnddate()), "create_time", request.getEnddate());
        Map<String, Object> query = new HashMap<>();
        query.put("limit", request.getSize() + "");
        query.put("page", request.getIndex() + "");
        List<OutOrderEntity> result = outOrderService.selectPage(new Query<OutOrderEntity>(query).getPage(), condition).getRecords();
        if (result != null && result.size() > 0) {
            result.stream().forEach(x -> {
                ListOutOrderDTO dto = new ListOutOrderDTO();
                dto.setCode(x.getOrderNo());
                dto.setCreatedate(x.getCreateTime());
                dto.setPositionsum("");//todo 这是啥？
                dto.setStatus(x.getStatus());
                dto.setStatusstr(OutOrderStatusEnum.getTextByValue(x.getStatus()));


                List<ListOutOrderDTO.OutOrderItemDTO> haha = new ArrayList<>();
                List<OutOrderItemEntity> items = outOrderItemService.selectList(Condition.create().eq("order_no", x.getOrderNo()));
                items.stream().forEach(y->{
                    ListOutOrderDTO.OutOrderItemDTO vo = new ListOutOrderDTO.OutOrderItemDTO();
                    BeanUtils.copyProperties(y, vo);
                    vo.setItemGuid(y.getItemGuid() + "-" + y.getBatchNo());
                    vo.setItemId(vo.getItemGuid());
                    haha.add(vo);
                });
                dto.setItems(haha);
                response.add(dto);
            });
        }
        return Response.ok(response);
    }


    @WebApi
    @PostMapping("getoutofwarehousebycode")
    @ApiOperation("根据单号获取出库单详情")
    public Response getoutofwarehousebycode(@RequestBody DetailInOrderReq request) {
        OutOrderDTO response = new OutOrderDTO();
        if (StringUtils.isNotEmpty(request.getCode())) {
            List<OutOrderEntity> res = outOrderService.selectList(Condition.create().eq("order_no", request.getCode()).orderBy("id", false));
            if (res != null && res.size() > 0) {
                OutOrderEntity one = res.get(0);
                response.setCode(one.getOrderNo());
                response.setCreatedate(one.getCreateTime());
                response.setPositionsum("");
                response.setStatus(one.getStatus());
                response.setStatusStr(OutOrderStatusEnum.getTextByValue(one.getStatus()));

                List<OutOrderDTO.OutOrderItemDTO> haha = new ArrayList<>();
                List<OutOrderItemEntity> items = outOrderItemService.selectList(Condition.create().eq("order_no", one.getOrderNo()));
                items.stream().forEach(x->{
                    OutOrderDTO.OutOrderItemDTO vo = new OutOrderDTO.OutOrderItemDTO();
                    BeanUtils.copyProperties(x, vo);
                    vo.setItemGuid(x.getItemGuid() + "-" + x.getBatchNo());
                    vo.setItemId(vo.getItemGuid());
                    haha.add(vo);
                });
                response.setItems(haha);
            }
        }
        return Response.ok(response);
    }

//    @WebApi
//    @PostMapping("uploadoutofwarehouseresult")
//    @ApiOperation("上传出库拣货结果")
//    public Response uploadoutofwarehouseresult(@RequestBody UpdateOutOrderReq request) {
//
//        if (StringUtils.isNotEmpty(request.getCode())) {
//
//        } else {
//            return Response.fail("单号不能为空");
//        }
//
//        return Response.ok("接口迁移，请统一使用updateStep接口");
//    }


}
